import React from "react";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Checkbox, Form, Input, Flex } from "antd";
import "./index.scss";
import axios from "axios";
import { useNavigate } from "react-router-dom";
const Login = () => {
  const navigator = useNavigate();
  const onFinish = (values) => {
    //对登录校验的模拟 返回的数据是当当前登录用户的用户信息
    axios
      .get(`http://localhost:3000/users?username=${values.username}&roleState=true&_expand=role`)
      .then((res) => {
        console.log(res.data);
        // 找到匹配的用户并验证密码
        const user = res.data.find(
          (user) =>
            user.username === values.username &&
            String(user.password) === String(values.password)
        );

        if (!user) {
          alert("用户名或密码错误");
        } else {
          localStorage.setItem("token", JSON.stringify(user)); //将取出的对象当作token保存
          navigator("/");
        }
      });
  };
  //登录校验 （因为jsonserver不能模拟登录处理post请求 所以只能使用get请求用户列表数据来判断）
  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
      }}
    >
      <div className="formContainer">
        <div className="title">全球新闻发布系统</div>
        <Form
          name="login"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名!" }]}
          >
            <Input prefix={<UserOutlined />} placeholder="Username" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码!" }]}
          >
            <Input
              prefix={<LockOutlined />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>
          <Form.Item>
            <Flex justify="space-between" align="center">
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住密码</Checkbox>
              </Form.Item>
              <a href="">取消默认登录</a>
            </Flex>
          </Form.Item>
          <Form.Item>
            <Button block type="primary" htmlType="submit">
              确认登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
export default Login;
